package com.example.util.task;

import com.example.util.service.TerminalManageServiceImpl;
import com.example.util.util.FileUtil;
import com.example.util.util.NumberUtil;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 批量处理工具类
 */
@Slf4j
@Component("tempMobileBatchImpl")
public class TempMobileBatchImpl {

    private static final Integer mobileSize = 100;
    public static final RateLimiter limiter = RateLimiter.create(50);

    /**
     * 大批量拆分小批量
     *
     * @param lists 批量处理数据
     * @param <T>
     */
    public <T> void listBatchForMobile(List<T> lists, String fileName, String fileWriterDir, String terminalManageUrl, String token) {


        // 判断集合数量，如果小于等于定义的数量（即未达到批处理条件），直接进行处理

        if (lists.size() <= mobileSize) {

            if (log.isDebugEnabled()) {
                log.debug("批次处理未达到分批条件,本批次数据量{}", lists.size());
            }
            //直接处理业务
            doingBusi((List<String>) lists, fileName, fileWriterDir, terminalManageUrl, token);
            return;
        }
        // 如果大于定义的数量，按定义数量进行批处理
        int times = lists.size() / mobileSize + 1;
        Thread t = Thread.currentThread();
        if (log.isDebugEnabled()) {
            log.debug("线程名:{}_一共要进行{}次批处理", t.getName(), times);
        }
        // 遍历分批处理次数，并进行批处理
        for (int i = 0; i < times; i++) {
            limiter.acquire();
            // 定义要进行批处理的临时集合
            List<T> tempList = new ArrayList<>(mobileSize);
            // 将要批处理数据放入临时集合中
            for (int j = i * mobileSize; j < lists.size(); j++) {
                tempList.add(lists.get(j));
                if (tempList.size() == mobileSize) {
                    break;
                }
            }

            // 进行批处理
            if (log.isDebugEnabled()) {
                log.debug("线程名:{}_进行第{}次批处理,本批次数量{}", t.getName(), i + 1, tempList.size());
            }
            Boolean aBoolean = doingBusi((List<String>) tempList, fileName, fileWriterDir, terminalManageUrl, token);
        }
    }

    /**
     * 处理临时白名单转换业务
     *
     * @param lists
     * @return
     */
    private Boolean doingBusi(List<String> lists, String fileName, String fileWriterDir, String terminalManageUrl, String token) {

        //获取文件名
        String a = fileName.substring(fileName.lastIndexOf("/"));
        List<String> sucessList = new ArrayList();
        //1.调用后置查询批次中数手机号在运营商侧白名单情况
        if (!CollectionUtils.isEmpty(lists)) {
            sucessList = TerminalManageServiceImpl.queryTerminalManageV2(lists, terminalManageUrl, token);
        }
        if (sucessList == null) {
            log.info("运营商接口调用返回失败或超时，进行补偿");
            //TODO:错误的补偿
            Map<String, List<String>> wrongMap = lists.stream().collect(Collectors.groupingBy(item -> {
                return item.substring(0, 3);
            }));
            Iterator<String> iterator = wrongMap.keySet().iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                FileUtil.put2File(a, wrongMap.get(next), "/opt/app/rms_fg/util-white/error/" + next);
            }

            return Boolean.FALSE;
        }
        if (CollectionUtils.isEmpty(sucessList)) {
            log.info("成功数据为空");
        }
        List finalSucessList = sucessList;
        List<String> noHitList = lists.stream().filter(item -> !finalSucessList.contains(item)).collect(Collectors.toList());
        if (noHitList == null) {
            noHitList = new ArrayList<>(1);
        }

//        //进行成功文件写入操作
//        FileUtil.put2File(a, sucessList, fileWriterDir);
//        //进行未命中手机号写入操作
//        FileUtil.put2File(a, noHitList, fileWriterDir + "/no-hitting");
        Map<String, List<String>> sucessMap = sucessList.stream().collect(Collectors.groupingBy(item -> item.substring(0, 3)));
        Map<String, List<String>> noHitMap = noHitList.stream().collect(Collectors.groupingBy(item -> item.substring(0, 3)));
        Iterator<String> iterator = sucessMap.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            FileUtil.put2File(a, sucessMap.get(next), fileWriterDir + "/" + next);
        }
        Iterator<String> iterator2 = noHitMap.keySet().iterator();
        while (iterator2.hasNext()) {
            String next = iterator2.next();
            FileUtil.put2File(a, noHitMap.get(next), fileWriterDir + "/" + next + "/no-hitting");
        }
        return true;
    }

    /**
     * 大批量拆分小批量（ 手机号后八位生成 ）
     *
     * @param i
     * @param writeDir
     */
    public void listBatchForMobileNextEight(Integer i, String writeDir) {

        // 判断集合数量，如果小于等于定义的数量（即未达到批处理条件），直接进行处理
        Integer taskInitNum = (i - 1) * 100000;
        for (int j = 1; j <= 10; j++) {
            Integer beginNum = taskInitNum + (j - 1) * 10000;
            log.info("当前批次开始字符:{}", beginNum);
            List<String> mobiles = NumberUtil.addFixLenthNumber(8, 10000, beginNum);
            String index = mobiles.get(mobiles.size() - 1);
            log.info("当前批次最后一个数据:{}", Integer.valueOf(index));
            FileUtil.put2File(index + ".txt", mobiles, writeDir);
        }
    }


}